import React, { useEffect } from 'react';
import { useParams } from 'react-router-dom';
import {
  Form,
  Input,
  Button,
  InputNumber,
  Card
} from 'antd';
import { message } from 'antd';

import { useAddShoppingCart } from '../../hook/add_shoppingCart';




const formItemLayout = {
  labelCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 8,
    },
  },
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 16,
    },
  },
};
const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 16,
      offset: 8,
    },
  },
};


// eslint-disable-next-line
export default () => {
  const params = useParams();
  const { _id } = params;

  const [{ user, seckill, count }, { getAddCartData, changeCount, addComm }] = useAddShoppingCart();
  console.log({ user, seckill, count });

  useEffect(() => {
    if (_id == ":_id") return;
    getAddCartData(_id);
  }, [])


  const [form] = Form.useForm();
  // 表单提交触发函数
  const onFinish = async () => {
    // 必须从秒杀页面跳转才能添加
    console.log(user.username);
    if (user.username) {
      await addComm();
      return message.success({ content: '新增成功!' });
    }
    return message.error('无法添加，需从商品页跳转');


  };

  // 数字框变化时回调
  const onChange = (count) => {
    changeCount(count);
  }


  return (
    <Card title="购物车新增" style={{ width: "100%" }}>

      <Form
        {...formItemLayout}
        form={form}
        name="register"
        onFinish={onFinish}
        style={{ width: 500 }}
        labelCol={{ span: 5, offset: 3 }}
      >
        <Form.Item
          label="用户："
          rules={[
            {
              required: true,
            },
          ]}
        >
          <Input value={user.username} disabled style={{ backgroundColor: "white", width: "300px", color: "#000" }} />
        </Form.Item>

        <Form.Item
          label="秒杀商品："
          rules={[
            {
              required: true,
            },
          ]}
        >
          <Input value={seckill.name} disabled style={{ backgroundColor: "white", width: "300px", color: "#000" }} />
        </Form.Item>

        <Form.Item
          label="数量："
          rules={[
            {
              required: true,
            },
          ]}
        >
          <InputNumber min={1} max={seckill.restricted} value={count} onChange={onChange} />
        </Form.Item>

        <Form.Item {...tailFormItemLayout}>
          <Button type="primary" htmlType="submit">
            新增
          </Button>
        </Form.Item>
      </Form >
    </Card >
  )
}